/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worlds;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import net.worlds.input.InputState;
import net.worlds.net.ChatMessage;
import net.worlds.object.Box;
import net.worlds.object.Tool;
import net.worlds.ui.UI;
import net.worlds.ui.edge.EMain;
import net.worlds.ui.edge.EditorOverlay;
import net.worlds.ui.edge.EditorTop;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2D;

/**
 *
 * @author Jacob
 */
public class EditorView extends MainView{
    private final Color gridColor = new Color(64, 64, 64, 64);
    public EditorView()
    {
        topUI = new EditorTop(this, width, height);
        overlayUI = new EditorOverlay(this, width, height);
        Main.loading = false;
    }
    public void onCreated()
    {
        ((EditorTop)topUI).showAdvancedTools();
    }
    protected void drawGameUI(Graphics2D g, World world, int viewWidth, int viewHeight, float worldWidth, float worldHeight)
    {
        if(UI.mouseMode == UI.MODE_SCALE && UI.scaleBox != null)
        {
            Vec2D worldVec = new Vec2D(InputState.mouseX, InputState.mouseY).screenToWorld();
            if(UI.snapToGrid)
                worldVec = worldVec.round();
            g.setColor(selectionRectBorderColor);

            Box box = UI.scaleBox;
            Vec2D local = box.getBody().getLocalPoint(worldVec);
            Vec2D opposite = UI.scaleOppositeVert;
            Vec2D distance = new Vec2D(local.sub(opposite)).abs();
            Vec2D pos = worldVec.add(new Vec2D(box.getBody().getWorldPoint(opposite))).div(2);

            AffineTransform oldTransform = g.getTransform();

            Vec2D imgPos = new Vec2D(pos.x - distance.x * 0.5f, pos.y + distance.y * 0.5f).worldToScreen(this);
            Vec2D rotateCenter = pos.worldToScreen(this);
            Vec2D screenSize = distance.toScreenUnits();

            int ix = (int) imgPos.x;
            int iy = (int) imgPos.y;
            int ssx = (int) screenSize.x;
            int ssy = (int) screenSize.y;
            if(box.getBody().getAngle() != 0.0)
            {
                AffineTransform rotate = AffineTransform.getRotateInstance(-box.getBody().getAngle(), rotateCenter.x, rotateCenter.y);
                g.setTransform(rotate);
            }
            g.drawRect(ix, iy, ssx, ssy);
            g.setTransform(oldTransform);
        }
        if(UI.mouseMode == UI.MODE_ROPE && InputState.mouseButton == 1 && !UI.mouseClickUI)
        {
            Vec2D start = new Vec2D(InputState.mouseClickX, InputState.mouseClickY);
            Vec2D stop = new Vec2D(InputState.mouseX, InputState.mouseY);
            g.setColor(selectionRectBorderColor);
            g.drawLine((int) start.x, (int) start.y, (int)stop.x, (int) stop.y);
        }
        if(UI.drawingTriangle)
        {
            int[] xPoints = new int[3];
            int[] yPoints = new int[3];
            xPoints = new int[]{InputState.mouseX, InputState.mouseClickX, InputState.mouseClickX};
            yPoints = new int[]{InputState.mouseY, InputState.mouseClickY, InputState.mouseY};
            Color color = UI.getNextObjectColor();
            g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 128));
            g.fillPolygon(xPoints, yPoints, 3);
        }
        if((UI.mouseMode == UI.MODE_ARROW || UI.drawingBox) && InputState.mouseButton == 1 && !UI.isDraggingPart() && (Main.getLocalPlayer() == null || Main.getLocalPlayer().getSelectedTool() == null))
        {
            int startX;
            int startY;
            int stopX;
            int stopY;
            if(InputState.mouseClickX < InputState.mouseX)
            {
                startX = InputState.mouseClickX;
                stopX = InputState.mouseX;
            }
            else
            {
                startX = InputState.mouseX;
                stopX = InputState.mouseClickX;
            }
            if(InputState.mouseClickY < InputState.mouseY)
            {
                startY = InputState.mouseClickY;
                stopY = InputState.mouseY;
            }
            else
            {
                startY = InputState.mouseY;
                stopY = InputState.mouseClickY;
            }
            if(UI.drawingBox)
            {
                Vec2D startWorld = new Vec2D(startX, startY).screenToWorld();
                Vec2D stopWorld = new Vec2D(stopX, stopY).screenToWorld();
                Color c = UI.getNextObjectColor();
                g.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 127));
                if(UI.snapToGrid)
                {
                    if(stopX > startX)
                    {
                        startWorld.x = MathUtils.floor(startWorld.x);
                        stopWorld.x = MathUtils.ceil(stopWorld.x);
                    }
                    else
                    {
                        startWorld.x = MathUtils.ceil(startWorld.x);
                        stopWorld.x = MathUtils.floor(stopWorld.x);
                    }
                    if(stopY > startY)
                    {
                        startWorld.y = MathUtils.ceil(startWorld.y);
                        stopWorld.y = MathUtils.floor(stopWorld.y);
                    }
                    else
                    {
                        startWorld.y = MathUtils.floor(startWorld.y);
                        stopWorld.y = MathUtils.ceil(stopWorld.y);
                    }
                    Vec2D start = startWorld.worldToScreen(this);
                    Vec2D stop = stopWorld.worldToScreen(this);
                    startX = (int) start.x;
                    startY = (int) start.y;
                    stopX = (int) stop.x;
                    stopY = (int) stop.y;
                }
            }
            else
                g.setColor(selectionRectBackgroundColor);
            int width = stopX - startX;
            int height = stopY - startY;
            if(UI.mouseMode == UI.MODE_LADDER)
            {
                width = (int) (4 * scaleFactor);
                if(startX < InputState.mouseClickX)
                {
                    startX = InputState.mouseClickX;
                }
                startX -= width;
            }
            if(!UI.mouseClickUI)
            {
                g.fillRect(startX, startY, width, height);
                g.setColor(selectionRectBorderColor);
                if(!UI.drawingBox)
                    g.drawRect(startX, startY, width, height);
            }
        }
        if(UI.drawingCircle)
        {
            int x = InputState.mouseX - InputState.mouseClickX;
            int y = InputState.mouseY - InputState.mouseClickY;
            Vec2D worldVec = new Vec2D(x, y).screenToWorld();
            if(UI.snapToGrid)
                worldVec = worldVec.round();
            worldVec = worldVec.worldToScreen(this);
            int a = (int) worldVec.x;
            int b = (int) worldVec.y;
            int distance = (int) MathUtils.sqrt(a*a + b*b);
            int width = distance * 2;
            int height = distance * 2;
            Vec2D mouseVec = new Vec2D(InputState.mouseClickX, InputState.mouseClickY).screenToWorld();
            mouseVec = mouseVec.worldToScreen(this);
            int topX = (int) (mouseVec.x - distance);
            int topY = (int) (mouseVec.y - distance);
            Color color = UI.getNextObjectColor();
            g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 128));
            g.fillOval(topX, topY, width, height);
        }
        if(Main.getLocalPlayer() != null)
        {
            LocalPlayer player = Main.getLocalPlayer();
            int startX = 25;
            int i = 1;
            for(Tool t : player.getTools())
            {
                BufferedImage img = t.getImage();
                if(img == null)
                    continue;
                int imgWidth = img.getWidth();
                int imgHeight = img.getHeight();
                if(t == player.getSelectedTool())
                    g.setColor(selectedToolColor);
                else
                    g.setColor(defaultToolColor);
                String n = t.toString();
                int rectWidth = imgWidth;
                Rectangle2D bounds = g.getFontMetrics().getStringBounds(n, g);
                if(bounds.getWidth() > imgWidth)
                    rectWidth = (int) bounds.getWidth();
                int yOffset = 25;
                g.fillRoundRect(startX, 10 + yOffset, rectWidth + 40, imgHeight + 40 + 10, 10, 10);
                g.drawImage(img, startX + 20, 40 + yOffset, null);
                g.setColor(Color.white);
                g.drawString(n, startX + 20, imgHeight + 55 + yOffset);
                g.drawString(Integer.toString(i), startX + 4, 45 + yOffset);
                startX += rectWidth + 40 + 10;
                i++;
            }
        }
        if(Main.getPlayer() != null && Main.getPlayer().getMessage() != null)
        {
            String m = Main.getPlayer().getMessage();
            g.setFont(messageFont);
            Rectangle2D rect = g.getFontMetrics().getStringBounds(m, g);
            g.setColor(selectionRectBackgroundColor);
            g.fillRect(0, viewHeight - 50, viewWidth, 50);
            int textX = (int) (viewWidth / 2 - rect.getWidth() / 2);
            int textY = viewHeight - 15;
            g.setColor(Color.black);
            g.drawString(m, textX + 1, textY + 1);
            g.setColor(Color.white);
            g.drawString(m, textX, textY);
        }
        double scale = scaleFactor;
        if(UI.showGrid == true && scale > 4)
        {
            g.setColor(gridColor);
            Vec2D lower = new Vec2D(getCamPosition().x - worldWidth / 2, getCamPosition().y - worldHeight / 2);
            Vec2D upper = new Vec2D(getCamPosition().x + worldWidth / 2, getCamPosition().y + worldHeight / 2);
            for(float x = MathUtils.floor(lower.x); x < upper.x; x++)
            {
                int sx = (int) new Vec2D(x, 0f).worldToScreen(this).x;
                g.drawLine(sx, (int) upper.worldToScreen(this).y, (int) sx, (int) (lower.worldToScreen(this).y));
            }
            for(float y = MathUtils.floor(lower.y); y < upper.y; y++)
            {
                int sy = (int) new Vec2D(0f, y).worldToScreen(this).y;
                g.drawLine((int) lower.worldToScreen(this).x, (int) sy, (int) upper.worldToScreen(this).x, (int) sy);
            }
        }

        if(AssetLoader.getInstance().isBusy())
        {
            int astartX = 5;
            int startY = height - 20;
            g.setColor(defaultToolColor);
            g.fillRect(astartX, startY, 50, 15);
            int[] data = AssetLoader.getInstance().getInfo();
            double percent;
            if(data[0] == 0)
                percent = 0;
            else
                percent = (double)data[1]/data[0];
            int barWidth = (int) (50 * percent);
            g.setColor(selectedToolColor);
            g.fillRect(astartX, startY, barWidth, 15);
        }
        if(world.getMessage() != null)
        {
            String m = world.getMessage();
            g.setFont(messageFont);
            Rectangle2D rect = g.getFontMetrics().getStringBounds(m, g);
            g.setColor(selectionRectBackgroundColor);
            g.fillRect(0, 0,viewWidth, viewHeight);
            int textX = (int) (viewWidth / 2 - rect.getWidth() / 2);
            int textY = (int) (viewHeight / 2 + rect.getHeight() / 2);
            g.setColor(Color.black);
            g.drawString(m, textX + 1, textY + 1);
            g.setColor(Color.white);
            g.drawString(m, textX, textY);
        }
        ChatMessage[] chats = Chat.getChats();
        int chatStartY = height/2;
        int chatY = chatStartY;
        for(int i = chats.length - 1; i > -1; i--)
        {
            if(chats[i] != null && chats[i].getAge() < 60 * 1000 || !Main.chatBarText.equals("Press . to chat"))
            {
                String m = chats[i].getMessage();
                g.setFont(defaultFont);
                g.setColor(transparentBlack);
                g.drawString(m, 41, chatY + 1);
                g.setColor(chats[i].getColor());
                g.drawString(m, 40, chatY);
                chatY -= 18;
            }
            else
                break;
        }
        if(Main.getLocalPlayer() != null)
        {
            g.setColor(Color.black);
            g.fillRect(0, height - 16, width, 16);
            g.setColor(Color.white);
            g.setFont(defaultFont);
            if(Main.chatBarText.equals("Press . to chat"))
                g.drawString(Main.chatBarText, 5, height - 3);
            else
                g.drawString(Main.chatBarText+"_", 5, height - 3);
        }
        if(Stats.showStats)
        {
            int y = 100;
            drawText(g, "FPS: "+Stats.fps, 50, y);
            y += 20;
            drawText(g, "# Bodies: "+Stats.numBodies, 50, y);
            y += 20;
            drawText(g, "# Pairs: "+Stats.numPairs, 50, y);
            y += 20;
            drawText(g, "# Proxies: "+Stats.numProxies, 50, y);
            y += 20;
            drawText(g, "# Contacts: "+Stats.numContacts, 50, y);
            y += 20;
            drawText(g, "# Joints: "+Stats.numJoints, 50, y);
            y += 20;
            drawText(g, "# Objects: "+Stats.numObjects, 50, y);
            y += 20;
            drawText(g, "Task Queue Size: "+Stats.taskQueueSize, 50, y);

        }
        BufferedImage mouse = UI.getMouseImage();
        if(mouse != null && UI.mouseInside)
        {
            if(UI.cursor == UI.crosshairCursor)
                g.drawImage(mouse, InputState.mouseX + 10, InputState.mouseY + 8, null);
            else
                g.drawImage(mouse, InputState.mouseX + 15, InputState.mouseY + 8, null);
        }
    }
    @Override
    public EMain getOverlay() {
        return overlayUI;
    }

    @Override
    public EMain getTop() {
        return topUI;
    }
    public boolean eMouseDown(int b, int x, int y)
    {
        if(getTop().eMouseDown(b, x, y))
            return true;
        else if(getOverlay().eMouseDown(b, x, y))
            return true;
        else
            return false;
    }
    public boolean eMouseUp(int b, int x, int y)
    {
        if(getTop().eMouseUp(b, x, y))
            return true;
        else if(getOverlay().eMouseUp(b, x, y))
            return true;
        else
            return false;
    }
    public boolean eMouseMove(int x, int y)
    {
        if(getTop().eMouseMove(x, y))
            return true;
        else if(getOverlay().eMouseMove(x, y))
            return true;
        else
            return false;
    }
    public boolean eMouseDrag(int b, int x, int y)
    {
        if(getTop().eMouseDrag(b, x, y))
            return true;
        else if(getOverlay().eMouseDrag(b, x, y))
            return true;
        else
            return false;
    }
}
